package com.neusoft.bizcore.activiti.converter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.activiti.dto.ProcessFormDTO;
import com.neusoft.bizcore.activiti.dto.ProcessFormItemDTO;
import com.neusoft.bizcore.activiti.model.ProcessForm;
import com.neusoft.bizcore.activiti.repository.ProcessFormRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;

@Component
public class ProcessFormConverter extends AbstractConverter<ProcessForm, ProcessFormDTO> {

    @Autowired
    private ProcessFormRepository processFormRepository;
    @Autowired
    private ProcessFormItemConverter processFormItemConverter;

    @Override
    public ProcessForm toModel(final ProcessFormDTO dto) {
        ProcessForm model;

        if (dto.isNew()) {
            model = new ProcessForm();
        } else {
            model = this.processFormRepository.getOne(dto.getId());
        }

        model.setWorkType(dto.getWorkType());
        model.setCode(dto.getCode());
        model.setName(dto.getName());
        model.setType(dto.getType());

        return model;
    }

    @Override
    public ProcessFormDTO toDTO(final ProcessForm model, final boolean forListView) {

        final ProcessFormDTO dto = new ProcessFormDTO();

        dto.setId(model.getId());
        dto.setWorkType(model.getWorkType());
        dto.setCode(model.getCode());
        dto.setName(model.getName());
        dto.setType(model.getType());

        if (!forListView) {
            model.getItems().stream().map(k -> {

                final ProcessFormItemDTO item = this.processFormItemConverter.toDTO(k);
                item.setFormCode(model.getCode());
                item.setFormName(model.getName());

                return item;

            }).filter(m -> null != m)
                    .forEach(dto.getItems()::add);
        }

        return dto;
    }

}
